package authorized

import (
	"encoding/json"
	"fmt"
	"github.com/go-resty/resty/v2"
)

const (
	appAccessTokenURL      = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s"
	appMessageSubscribeURL = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=%s"
)

// 获取小程序授权access_token
func GetAppAccessToken(AppId, AppSecret string) (res ResAccessToken, err error) {
	var client = resty.New()

	urlStr := fmt.Sprintf(appAccessTokenURL, AppId, AppSecret)
	resp, err := client.R().Get(urlStr)
	if err != nil {
		return
	}
	err = json.Unmarshal(resp.Body(), &res)
	if err != nil {
		return
	}
	if res.Errcode != 0 {
		err = fmt.Errorf("GetUserAccessToken error : errcode=%v , errmsg=%v", res.Errcode, res.Errmsg)
		return
	}
	return
}

// 微信订阅消息推送
func MessageSubscribePost(accessToken string, data interface{}) (resData MessageSubscribePostResp, err error) {
	urlStr := fmt.Sprintf(appMessageSubscribeURL, accessToken)

	if resp, err := client.R().SetBody(data).Post(urlStr); err != nil {
		return resData, err
	} else {
		fmt.Println(string(resp.Body()))
		_ = json.Unmarshal([]byte(string(resp.Body())), &resData)
		return resData, nil
	}
}

type MessageSubscribePostResp struct {
	Errcode int    `json:"errcode"`
	Errmsg  string `json:"errmsg"`
	Msgid   string `json:"msgid"`
}
